package com.example.weather_location_service;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.example.weather_location_service.service.AutoUpateService;
import com.example.weather_location_service.util.HttpUtil;
import com.example.weather_location_service.util.Utility;
import com.example.weather_location_service.util.Weatherbean;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {
    private final String TAG = "WeatherActivtyccc";
    private TextView titleCity;
    private TextView titleUpdataTime;
    private TextView degreeText;
    private TextView weatherInfoText;
    private LinearLayout forecastLayour;
    private TextView aqiText;
    private TextView pm25Text;
    private TextView confortText;
    private TextView carWashText;
    private TextView sportText;
    private ScrollView weatherLayout;
    private ImageView bingPicImg;
    public SwipeRefreshLayout swipeRefrsh;
    private String mWeatherId;
    public DrawerLayout drawerLayout;
    private Button navButton;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_weather);
        initView();
        swipeRefrsh.setColorSchemeColors(Color.BLUE);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String bingPic = preferences.getString("bing_pic", null);
        if (bingPic != null) {
            Glide.with(this).load(bingPic).into(bingPicImg);
        } else {
            loadBingPic();
        }
        String watherString = preferences.getString("weather", null);
        if (watherString != null) {
//            有缓存时直接解析天气数据
            Weatherbean weatherbean = Utility.handleWeatherResponse(watherString);
            mWeatherId = weatherbean.getHeWeather().get(0).getBasic().getId();
            showWeatherInfo(weatherbean);
        } else {
            //无缓存时去服务器查询天气
            mWeatherId = getIntent().getStringExtra("weather_id");
            weatherLayout.setVisibility(View.INVISIBLE);
            requestWeather(mWeatherId);
        }
        swipeRefrsh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestWeather(mWeatherId);
            }
        });
    }

    /*
    加载每日一图
     */
    private void loadBingPic() {
        String requsetBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOKHttpRequest(requsetBingPic, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                final String bingPic = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                editor.putString("bing_pic", bingPic);
                editor.apply();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg);
                    }
                });
            }
        });
    }

    /*
    初始化控件
     */
    private void initView() {
        titleCity = (TextView) findViewById(R.id.title_city);
        titleUpdataTime = (TextView) findViewById(R.id.title_updata_time);
        degreeText = (TextView) findViewById(R.id.degree_text);
        weatherInfoText = (TextView) findViewById(R.id.weather_info_text);
        forecastLayour = (LinearLayout) findViewById(R.id.forecast_layour);
        aqiText = (TextView) findViewById(R.id.aqi_text);
        pm25Text = (TextView) findViewById(R.id.pm25_text);
        confortText = (TextView) findViewById(R.id.confort_text);
        carWashText = (TextView) findViewById(R.id.car_wash_text);
        sportText = (TextView) findViewById(R.id.sport_text);
        weatherLayout = (ScrollView) findViewById(R.id.weather_layout);
        bingPicImg = (ImageView) findViewById(R.id.bing_pic_img);

        swipeRefrsh = (SwipeRefreshLayout) findViewById(R.id.swipe_refrsh);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        navButton = (Button) findViewById(R.id.nav_button);
        navButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (drawerLayout.isDrawerOpen(Gravity.LEFT)){
                    drawerLayout.closeDrawers();
                }else {
                    drawerLayout.openDrawer(Gravity.LEFT);
                }
            }
        });
    }

    /*
    处理并展示Weatherbean实体类中的数据
     */
    private void showWeatherInfo(Weatherbean bean) {
        List<Weatherbean.HeWeatherBean> List = bean.getHeWeather();
        String cityName = List.get(0).getBasic().getCity();
        String updataTime = List.get(0).getBasic().getUpdate().getLoc();
        String degree = List.get(0).getNow().getTmp() + "°C";
        String weatherInfo = List.get(0).getNow().getCond().getTxt();
        titleCity.setText(cityName);
        titleUpdataTime.setText(updataTime);
        degreeText.setText(degree);
        weatherInfoText.setText(weatherInfo);
        forecastLayour.removeAllViews();
        for (Weatherbean.HeWeatherBean.DailyForecastBean forecast : List.get(0).getDaily_forecast()) {
            View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayour, false);
            TextView dataText = (TextView) view.findViewById(R.id.data_text);
            TextView infoText = (TextView) view.findViewById(R.id.info_text);
            TextView maxText = (TextView) view.findViewById(R.id.max_text);
            TextView minText = (TextView) view.findViewById(R.id.min_text);
            dataText.setText(forecast.getDate());
            infoText.setText(forecast.getCond().getTxt_d());
            maxText.setText(forecast.getTmp().getMax());
            minText.setText(forecast.getTmp().getMin());
            forecastLayour.addView(view);
        }
        if (List.get(0).getAqi() != null) {
            aqiText.setText(List.get(0).getAqi().getCity().getAqi());
            pm25Text.setText(List.get(0).getAqi().getCity().getPm25() + ",质量:" + List.get(0).getAqi().getCity().getQlty());
        }
        String comfort = "舒适度:" + List.get(0).getSuggestion().getComf().getBrf() + "," + List.get(0).getSuggestion().getComf().getTxt();
        String carwash = "洗车指数:" + List.get(0).getSuggestion().getCw().getBrf() + "," + List.get(0).getSuggestion().getCw().getTxt();
        String sport = "运动指数:" + List.get(0).getSuggestion().getSport().getBrf() + "," + List.get(0).getSuggestion().getSport().getTxt();
        confortText.setText(comfort);
        carWashText.setText(carwash);
        sportText.setText(sport);
        weatherLayout.setVisibility(View.VISIBLE);
        Intent intent=new Intent(this, AutoUpateService.class);
        startService(intent);
    }

    /*
    根据天气id请求城市天气数据
     */
    public void requestWeather(final String weatherId) {
        String weathUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=ddc74d3d55724ca5a4e8631422c27362";
        HttpUtil.sendOKHttpRequest(weathUrl, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
                        swipeRefrsh.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                final String responseText = response.body().string();
                final Weatherbean weatherbean = Utility.handleWeatherResponse(responseText);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        List<Weatherbean.HeWeatherBean> heWeatherBeanList = weatherbean.getHeWeather();
                        if (weatherbean != null && "ok".equals(heWeatherBeanList.get(0).getStatus())) {
                            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                            editor.putString("weather", responseText);
                            editor.apply();
                            mWeatherId = heWeatherBeanList.get(0).getBasic().getId();
                            showWeatherInfo(weatherbean);
                        } else {
                            Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
                        }
                        swipeRefrsh.setRefreshing(false);
                    }
                });
            }
        });
    }
}
